<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\model\Fareharbor as F;
use think\Cache;
use think\db;
use think\Exception;
use think\Request;
use think\Log;
use app\api\controller\Viator as V;
class FareGoods extends Api{

    protected $responseType = '';

    protected $fail_res = [];
    protected $success_res = [];
    public function __construct()
    {
        parent::__construct();
        $this->fail_res = ['code'=>-1,'msg'=>'获取数据失败'];
        $this->success_res = ['code'=>200,'msg'=>'获取数据成功','data'=>[]];
    }

    public function index()
    {

    }

    //清除fareharbor相关缓存
    public function clearFareCache()
    {
//        $cache = cache('fare_companies');
//        $cache = cache('fare_'.$company."_".$product);
//        $cache = cache('fare_'.$company.'_'.$item.'_'.$sdate.'_'.$edate);
//        $cache = cache('fare_'.$company.'_'.$item.'_'.$date);
//        $cache = cache("fare_".$company."_".$item."_180");
//        $cache = cache('fare_bodyglove_items');
//        var_dump($cache);exit;

        if(!cache('fare_companies')){
            $this->wirteFareLog("清除fare缓存已清除");
            return json(['code'=>'200','msg'=>'ko']);
            exit;
        }
        $this->wirteFareLog("清除fare缓存开始");
        $companies = (new F())->getFareharborData();
        foreach ($companies as $key => $value) {
            $company = $value['shortname'];
            $items = (new F())->getFareharborData([
                'company' => $value['shortname']
            ]);
            if (!empty($items)) {
                foreach ($items as $k => $v) {
                    $item = $v['pk'];
                    $start_time = time();
                    $end_time = strtotime("+181 day");
                    while($start_time < $end_time){
                        //清楚日期缓存
                        $date = date('Y-m-d',strtotime("+1 day",$start_time));
                        cache::rm('fare_'.$company.'_'.$item.'_'.$date);
                        $start_time = strtotime("+1 day",$start_time);
                    }
                    //清除商品缓存
                    cache::rm("fare_".$company."_".$item."_180");
                }
            }
            cache::rm('fare_'.$company."_items");
        }
        cache::rm('fare_companies');
        $this->wirteFareLog("清除fare缓存结束");
        return json(['code'=>'200','msg'=>'初步清除完毕']);
    }

    //获取合作商列表
    public function companiesList()
    {
        $companyList = (new F())->getFareharborData();
        $this->success_res['data'] = $companyList;
        return !empty($companyList)?json($this->success_res):json($this->fail_res);
    }
    //获取合作商的商品列表
    public function itemsList()
    {
        $post = request()->post();
        if(empty($post)){
            return json(['code'=>-1,'msg'=>'参数有误']);
        }
        $company = isset($post['company'])?$post['company']:"";
        if(empty($company)){
            return json(['code'=>-1,'msg'=>'请选择合作商']);
        }
        $itemsList = (new F())->getFareharborData(['company'=>$company],true);
        $this->success_res['data'] = $itemsList;
        return !empty($itemsList)?json($this->success_res):json($this->fail_res);
    }
    //获取合作商的商品 按照日期获取套餐信息
    public function proListByDate()
    {
        $post = request()->post();
        if(empty($post)){
            return json(['code'=>-1,'msg'=>'参数有误']);
        }
        $company = isset($post['company'])?$post['company']:"";
        $item = isset($post['company'])?$post['item']:"";
        $date = isset($post['date'])?$post['date']:"";
        if(empty($company)){
            return json(['code'=>-1,'msg'=>'请选择合作商']);
        }
        if(empty($item)){
            return json(['code'=>-1,'msg'=>'请选择项目']);
        }
        if(empty($date)){
            return json(['code'=>-1,'msg'=>'请选择日期']);
        }
        $productList = (new F())->getFareharborData(['company'=>$company,'item'=>$item,'date'=>$date]);
        $this->success_res['data'] = $productList;
        return !empty($productList)?json($this->success_res):json($this->fail_res);
    }
    //获取合作商的商品 按照日期区间获取套餐列表
    public function proListByDateRange()
    {
        $post = request()->post();
        if(empty($post)){
            return json(['code'=>-1,'msg'=>'参数有误']);
        }
        $company = isset($post['company'])?$post['company']:"";
        $item = isset($post['item'])?$post['item']:"";
        $sdate = isset($post['sdate'])?$post['sdate']:"";
        $edate = isset($post['edate'])?$post['edate']:"";
        if(empty($company)){
            return json(['code'=>-1,'msg'=>'请选择合作商']);
        }
        if(empty($item)){
            return json(['code'=>-1,'msg'=>'请选择项目']);
        }
        if(empty($sdate)){
            return json(['code'=>-1,'msg'=>'请选择开始日期']);
        }
        if(empty($edate)){
            return json(['code'=>-1,'msg'=>'请选择截至日期']);
        }
        $productList = (new F())->getFareharborData(['company'=>$company,'item'=>$item,'sdate'=>$sdate,'edate'=>$edate],true);
        $this->success_res['data'] = $productList;
        return !empty($productList)?json($this->success_res):json($this->fail_res);
    }
    //获取合作商的商品的具体信息
    public function productdetail()
    {
        $post = request()->post();
        if(empty($post)){
            return json(['code'=>-1,'msg'=>'参数有误']);
        }
        $company = isset($post['company'])?$post['company']:"";
        $product = isset($post['product'])?$post['product']:"";
        if(empty($company)){
            return json(['code'=>-1,'msg'=>'请选择合作商']);
        }
        if(empty($product)){
            return json(['code'=>-1,'msg'=>'请选择商品']);
        }
        $productinfo = (new F())->getFareharborData(['company'=>$company,'product'=>$product]);

        $this->success_res['data'] = $productinfo;
        return !empty($productinfo)?json($this->success_res):json($this->fail_res);
    }

    //获取单日套餐信息
    public function specsOneItem($company,$item,$date,$discount=1){
        $goodsList = (new F())->getFareharborData([
            'company'=>$company,
            'item'=>$item,
            'date'=>$date
        ]);
        $tax = $this->getItemTaxPercentage($company,$item);
        $exchange= db('exchange')->where('currency_code',"USD")->find();//汇率
        $tax = $tax>0?$tax:0;
        $sell_rate = db('viator_discount')->where("id=2 and status=1")->find();
        $sell_percent_rate = empty($sell_rate)&&$sell_rate['discount_num']?1:$sell_rate['discount_num'];
        foreach ($goodsList as $goods){
            $specs = $goods['customer_type_rates'];
            $person = [];
            foreach ($specs as $key=>$value){
                $usd_price = ceil($value['customer_prototype']['total']*(1+$tax/100)*100)/100;
                $person[] = [
                    'person_id'=>$value['pk'],
                    'person_name'=>$value['customer_prototype']['display_name'],
                    //'person_cname'=>$this->enTransChSpecName($value['customer_prototype']['display_name']),
                    'person_price'=>ceil($usd_price*$exchange['exchange_rate']*$discount*$sell_percent_rate*100)/100,
                    'person_num'=>empty($value['maximum_party_size'])?999:$value['maximum_party_size'],
                    'minorder_num'=>empty($value['minimum_party_size'])?1:$value['minimum_party_size'],
                    'inc_order_num'=>1,
                ];
            }
            //套餐名称 由时间字段截取字符串获取 格式 2010-01-01T00:00:00-1000
            //获取日期 01
            $start_day = substr($goods['start_at'],8,2);
            $end_day = substr($goods['end_at'],8,2);
            //获取时间 00:00
            $start_time = substr($goods['start_at'],11,5);
            $end_time = substr($goods['end_at'],11,5);
            if($start_day==$end_day){
                $specs_name = $start_time.'~'.$end_time;
            }else{
                $specs_name = $start_day.'日'.$start_time.'~'.$end_day.'日'.$end_time;
            }

            $result[] = [
                'specs_id'=>$goods['pk'],
                'specs_name'=>$specs_name,
                'person'=>$person,
                'gradeCode'=>''
            ];
        }

        return $result;
    }

    //获取商品税率
    public function getItemTaxPercentage($company,$item)
    {
        $items = (new F())->getFareharborData(['company'=>$company]);
        if(!empty($items)){
            foreach ($items as $key => $value){
                if($value['pk']==$item){
                    return $value['tax_percentage'];
                }
            }
            return -1;
        }else{
            return -1;
        }
    }

    //获取商品美元价格范围 输入为美分 输出为美元
    protected function getItemUsdMaxAndMinPrice($item)
    {
        $tax = !empty($item['tax_percentage'])?$item['tax_percentage']:0;
        $person = $item['customer_prototypes'];
        if(!empty($person)){
            $price = [];
            foreach ($person as $k=>$v){
                if($v['total'] > 0){
                    $price[] = ceil($v['total']*(1+$tax/100))/100;
                }
            }
            if(!empty($price)){
                return min($price).'~'.max($price);
            }else{
                return '';
            }
        }

    }

    //获取商品人民币价格范围 原输入为美元 输出为元
    protected function getItemCnyMaxAndMinPrice($item)
    {
        $exchange= db('exchange')->where('currency_code',"USD")->find();//汇率
        $tax = !empty($item['tax_percentage'])?$item['tax_percentage']:0;
        $person = $item['customer_prototypes'];
        if(!empty($person)){
            $price = [];
            foreach ($person as $k=>$v){
                if($v['total'] > 0){
                    $price[] = ceil($v['total']*(1+$tax/100)*$exchange['exchange_rate'])/100;
                }
            }
            if(!empty($price)){
                return min($price).'~'.max($price);
            }else{
                return '';
            }
        }

    }

    //获取商品售价范围
    public function getItemSellPrice($price_section)
    {
        $gain = db('viator_discount')->where('id=2 and status=1 and type="fareharbor"')->find();
        $section = explode('~',$price_section);
        if(!empty($gain) && count($section)==2){
            $percent = $gain['discount_num'];
            //汇率
            $exchange= db('exchange')->where('currency_code',"USD")->find();//汇率
            $min_price = ceil($section[0]*$exchange['exchange_rate']*$percent*100)/100;
            $max_price = ceil($section[1]*$exchange['exchange_rate']*$percent*100)/100;

            return $min_price.'~'.$max_price;
        }else{
            return $price_section;
        }

    }
    //获取商品的套餐信息
    public function getItemSpecsList($company,$item)
    {
        $cache = cache("fare_".$company."_".$item."_180");
        if(empty($cache)){
            $specs= $this->cacheEveryItemSpecs($company,$item);
        }else{
            $specs = json_decode($cache,true);
        }

        return $specs;
    }

    //获取100天的套餐信息 默认从今天开始
    public function getHundredProDetail($company,$item,$sdate='',$day='100',$is_flush=false)
    {
        $start_time = empty($sdate) ? time() : strtotime($sdate);
        $sdate = date("Y-m-d",strtotime('+1 day',$start_time));
        $day = !empty($day)?$day:'100';
        $edate = date("Y-m-d",strtotime("+".$day." day",$start_time));
        $proList = (new F())->getFareharborData([
            'company'   =>$company,
            'item'      =>$item,
            'sdate'     =>$sdate,
            'edate'     =>$edate
        ],$is_flush);
        if(empty($proList)){
            return [];
        }else{
            if($is_flush){
                //刷新每日缓存
                $this->cacheEverydaySpecs($company,$item,$proList);
            }

            $tax = $this->getItemTaxPercentage($company,$item);
            $tax = $tax>0?$tax:0;
            foreach ($proList as $key=>$value){
                $price = [];
                $specs = $value['customer_type_rates'];
                foreach ($specs as $k=>$v){
                    if($v['customer_prototype']['total']>0){
                        $price[] = ceil($v['customer_prototype']['total']*(1+$tax/100)*100)/100;
                    }
                }
                $min_price = empty($price)?0:min($price);
                $data[] = [
                    'pk'=>$value['pk'],
                    'time'=>substr($value['start_at'],0,10),
                    'min_price'=>$min_price,
                    'number'=>empty($value['maximum_party_size'])?999:$value['maximum_party_size'],
                ];
            }
            return $data;
        }

    }

    //缓存商品每天的套餐数据
    public function cacheEverydaySpecs($company,$item,$list)
    {
        $date_arr = [];
        foreach ($list as $key=>$value){
            $data = [];
            $date = substr($value['start_at'],0,10);
            $expire_time = date("Y-m-d",strtotime("+1 day",strtotime($date)));
            if(in_array($date,$date_arr)){
                $data = cache('fare_'.$company.'_'.$item.'_'.$date);
                $data = json_decode($data,true);
                array_push($data,$value);
            }else{
                array_push($date_arr,$date);
                $data[] = $value;
            }
            cache::set('fare_'.$company.'_'.$item.'_'.$date,json_encode($data),new \DateTime($expire_time));
            //$this->wirteFareLog($company."的".$item.'商品的'.$date.'套餐缓存更新成功');
        }

    }

    //缓存180天的商品套餐
    public function cacheEveryItemSpecs($company,$item)
    {
        //获取1-100天数据
        $firstData = $this->getHundredProDetail($company,$item,'','',true);
        //获取101-180天数据
        $sdate = date('Y-m-d',strtotime("+100 day",time()));
        $secondData = $this->getHundredProDetail($company,$item,$sdate,'80',true);

        $specs = array_merge($firstData,$secondData);
        //若商品180天内无套餐直接下架
        if(!empty($specs)){
            //刷新缓存时更新数据
            Cache::set("fare_".$company."_".$item.'_180',json_encode($specs));
            $this->wirteFareLog("item为".$item."的商品套餐缓存更新成功");
            //对商品进行上架操作
            $faregoods = db('fareharbor_goods')->field("fare_goods_id")->where(['item_id'=>$item,'company'=>$company,'status'=>'0'])->select();
            if(!empty($faregoods)){
                $msgs = [];
                foreach ($faregoods as $key=>$value){
                    $this->updSellFaregoods($company,$item);
                    $msgs[] = "item_id为".$item."的".$company."商品可售，请查看后上架";
                }
                //发送邮件给小美提示上架
                if(!empty($msgs)) (new \app\wap\controller\Notify())->kbxemailcode('Fareharbor商品可售通知',implode('<br>',$msgs),config('XIAOMEI_NOTICE_EMAIL'));
            }
        }else{
            $faregoods = db("fareharbor_goods")->where([
                'status'=>'1',
                'company'=>$company,
                'item_id'=>$item
            ])->select();
            if(!empty($faregoods)){
                //对商品进行下架操作
                $this->updNotSellFaregoods($company,$item);
            }
        }

        return $specs;
    }

    //更新商品为上架
    protected function updSellFaregoods($company,$item)
    {
        //fareharbor_goods应上架商品
        db('fareharbor_goods')->where(['item_id'=>$item,'company'=>$company])->update(['status'=>'1','update_time'=>time()]);
        $this->wirteFareLog("item为".$item."的".$company."商品套餐有数据，可以更新为上架");

    }
    //更新商品为下架
    protected function updNotSellFaregoods($company,$item)
    {
        //faregoods商品下架
        $faregoods = db('fareharbor_goods')->field("fare_goods_id")->where(['item_id'=>$item,'company'=>$company,'status'=>'1'])->select();
        if(!empty($faregoods)){
            //查找fareharbor_goods应下架商品的faregoodsid集合
            $fare_goods_ids = array_column($faregoods,'fare_goods_id');
            if(!empty($fare_goods_ids)){
                //fareharbor_goods应下架商品
                db('fareharbor_goods')->where(['item_id'=>$item,'company'=>$company,'status'=>'1'])->update(['status'=>'0','update_time'=>time()]);
                //goods应下架商品
                db('goods')->where(['source_id'=>['in',$fare_goods_ids],'standard_pro'=>'1','channel_source'=>'fareharbor'])->update(['goods_status'=>2]);
                //发送邮件给小美提示下架
                (new \app\wap\controller\Notify())->kbxemailcode('Fareharbor商品下架通知',"item_id为".$item."的".$company."商品因无套餐下架，下架时间是：".date("Y-m-d H:i:s"),config('XIAOMEI_NOTICE_EMAIL'));
                //商品下架通知
                $this->wirteFareLog("item_id为".$item."的".$company."商品因无套餐下架，下架时间是：".date("Y-m-d H:i:s"));
            }
        }
    }

    //刷新fareharbor表中的数据 先对比表中数据是否存在更新 然后执行新数据插入操作
    public function updateFareGoodsTableData(){
        ignore_user_abort();//关闭浏览器仍然执行
        set_time_limit(0);//程序运行不停止
        db::startTrans();
        try {
            $this->wirteFareLog("开始更新fareharbor数据表");
            $allItemID = db("fareharbor_goods")->field('item_id')->select();
            $allItemID = array_column($allItemID,'item_id');
            $where['status'] = 1;
            $goods = db("fareharbor_goods")->where($where)->select();
            //获取远程数据data
            $data = [];
            //合作商
            $companies = (new F())->getFareharborData([], true);
            foreach ($companies as $key => $value) {
                $items = (new F())->getFareharborData([
                    'company' => $value['shortname']
                ], true);
                $this->wirteFareLog("获取".$value['shortname']."的items成功");
                if (!empty($items)) {
                    foreach ($items as $k => $v) {
                        $items[$k]['company'] = $value['shortname'];
                    }
                }
                $data = array_merge($data, $items);
            }
            $this->wirteFareLog("获取".count($data)."条数据");
            $add_data = [];
            if (empty($data)) {
                $this->wirteFareLog("数据刷新失败,获取商品列表为空");
                return json(['code'=>-1,'msg'=>"数据刷新失败,获取商品列表为空"]);
            } elseif(empty($goods)){
                foreach ($data as $k => $v) {
                    if(!in_array($v['pk'],$allItemID)){
                        $company = $v['company'];
                        unset($v['company']);
                        $add_data[] = $this->insertFaregoods($v,$company);
                    }
                }
            }else{
                //遍历更新数据
                foreach ($goods as $i => $g) {
                    //初始状态为0 表示为下架如找到匹配数据修改为上架
                    $status = 0;
                    foreach ($data as $kk => $vv) {
                        //找到匹配数据
                        if ($g['item_id'] == $vv['pk'] && $g['company'] == $vv['company']) {
                            //数据匹配成功
                            $status = 1;
                            //标识数据匹配 用于下次循环寻找新数据 执行插入操作
                            $company = $vv['company'];
                            unset($vv['company']);
                            //数据有修改
                            if (json_encode($vv) != $g['item_json']) {
                                $this->wirteFareLog("item_id为{$vv['pk']}的商品数据有更新");
                                $vv['company'] = $company;
                                $this->updateFareharborGoods($g, $vv);
                            }

                            //补充数据 便于寻找未匹配的数据
                            $data[$kk]['company'] = $company;
                            $data[$kk]['is_selected'] = 1;
                            break;
                        }
                    }

                    //若未匹配成功 表示已下架
                    if ($status == 0) {
                        db("fareharbor_goods")->where("fare_goods_id", $g['fare_goods_id'])->update(['is_update'=>1,'update_desc'=>'商品已下架,下架时间是:'.date("Y-m-d H:i:s"),'status' =>'0', 'update_time' => time()]);
                    }
                }
                //执行新数据插入操作
                foreach ($data as $k => $v) {
                    $company = $v['company'];
                    if (!isset($v['is_selected'])) {
                        //插入数据
                        //$usd_price_section = $this->getItemUsdMaxAndMinPrice($v);
                        unset($v['company']);
                        $add_data[] = $this->insertFaregoods($v,$company);
                    }
                }
            }
            $this->wirteFareLog("剩余".count($add_data)."条新数据");
            if (!empty($add_data)) {
                foreach ($add_data as $a_k=>&$a_v){
                    if(in_array($a_v['item_id'],$allItemID)){
                        unset($add_data[$a_k]);
                    }
                }
                if(!empty($add_data)){
                    db('fareharbor_goods')->insertAll($add_data);
                }
            }

            //提交
            db::commit();
            //执行缓存操作
            if (!empty($add_data)) {
                foreach ($add_data as $kk=>$vv){
                    $this->wirteFareLog("插入item_id为".$vv['item_id']."的".$vv['company'].'商品成功');
                    //执行缓存操作
                    $this->cacheEveryItemSpecs($vv['company'], $vv['item_id']);
                }
            }
            $this->wirteFareLog("更新faregoods数据表结束");
            //数据更新完毕 同步价格
            $this->syncUpdGoodsPriceByFareharbor();
            $this->wirteFareLog("goods表关联价格更新结束");
            return json_encode(['code'=>200,'msg'=>'更新数据成功']);
        }catch(\Exception $e){
            //回滚
            db::rollback();
            $this->wirteFareLog("更新faregoods数据表失败,原因是".$e->getMessage());
            return json_encode(['code'=>-1,'msg'=>'更新数据失败,原因是'.$e->getMessage()]);
        }
    }

    //执行价格缓存
    public function updFareAllGoodsPrice()
    {
        $goodsList = db('fareharbor_goods')
            ->field("company,item_id")
            ->where('status','1')->select();
        if(!empty($goodsList)){
            try{
                $this->wirteFareLog("开始缓存fareharbor商品价格");
                foreach ($goodsList as $key=>$value){
                    //执行缓存操作
                    $this->cacheEveryItemSpecs($value['company'], $value['item_id']);
                }
                $this->wirteFareLog("缓存fareharbor商品价格结束");
                $this->wirteFareLog("开始更新goods关联的fareharbor商品价格");
                $this->syncUpdGoodsPriceByFareharbor();
                $this->wirteFareLog("更新goods关联的fareharbor商品价格结束");
            }catch(Exception $e){
                $this->wirteFareLog("缓存fareharbor商品价格意外中止,".$e->getMessage());
            }
        }
    }
    //对fareharbor插入新数据
    public function insertFaregoods($v,$company)
    {
        $usd_price_section = $this->getItemUsdMaxAndMinPrice($v);
        $add_data = [
            'item_id' => $v['pk'],
            'company' => $company,
            'item_name' => $v['name'],
            'image_cdn_url' => $v['image_cdn_url'],
            'cancellation_policy_safe_html' => $v['cancellation_policy_safe_html'],
            'images' => !empty($v['images']) ? json_encode($v['images']) : "",
            'locations' => json_encode($v['locations']),
            'headline' => $v['headline'],
            'description_safe_html' => $v['description_safe_html'],
            'booking_notes' => $v['booking_notes'],
            'location' => $v['location'],
            'description_text' => $v['description_text'],
            'customer_prototypes' => json_encode($v['customer_prototypes']),
            'tax_percentage' => $v['tax_percentage'],
            'usd_price_section' => $usd_price_section,
            'item_json' => json_encode($v),//记得unset(company)
            'update_time' => time(),
            'is_update'=>0,
            'update_desc'=>'##'.date('Y-m-d H:i:s').'----新增数据'
        ];

        return $add_data;
    }
    //对比fareharbor商品更新数据
    protected function updateFareharborGoods($g,$item)
    {
        //只有已关联的fareharbor商品才会有更新提醒
        $link_source = db("goods")->field('source_id')->where([
            'standard_pro'=>1,
            'channel_source'=>'fareharbor'
        ])->select();
        $link_source_ids = [];
        if(!empty($link_source)){
            $link_source_ids = array_column($link_source,'source_id');
        }
        //通知消息
        $msg = [];
        //税率是否修改
        $update_tax = 0;
        //价格是否修改
        $update_price = 0;
        if($g['item_name']!=$item['name']){
            $new_data['item_name'] = $item['name'];
            $msg[] = '名称item_name有更新,由原来的'.$g['item_name'].'更新为'.$new_data['item_name'];
        }
        if($g['image_cdn_url']!=$item['image_cdn_url']){
            $new_data['image_cdn_url'] = $item['image_cdn_url'];
            $msg[] = '图片地址image_cdn_url有更新';
        }
        if($g['cancellation_policy_safe_html']!=$item['cancellation_policy_safe_html']){
            $new_data['cancellation_policy_safe_html'] = $item['cancellation_policy_safe_html'];
            $msg[] = '退款说明cancellation_policy_safe_html有更新';
        }
        if(!empty($item['images']) && $g['images']!=json_encode($item['images'])){
            $new_data['images'] = json_encode($item['images']);
            $msg[] = '图片集合images有更新';
        }
        if($g['locations']!=json_encode($item['locations'])){
            $new_data['locations'] = json_encode($item['locations']);
            $msg[] = '地址locations有更新';
        }
        if($g['headline']!=$item['headline']){
            $new_data['headline'] = $item['headline'];
            $msg[] = '售卖时间headline有更新';
        }
        if($g['description_safe_html']!=$item['description_safe_html']){
            $new_data['description_safe_html'] = $item['description_safe_html'];
            $msg[] = '商品简介description_safe_html有更新';
        }
        if($g['booking_notes']!=$item['booking_notes']){
            $new_data['booking_notes'] = $item['booking_notes'];
            $msg[] = '备注booking_notes有更新';
        }
        if($g['location']!=json_encode($item['location'])){
            $new_data['location'] = json_encode($item['location']);
            $msg[] = '地址信息location有更新';
        }
        if($g['description_text']!=$item['description_text']){
            $new_data['description_text'] = $item['description_text'];
            $msg[] = '详情description_text有更新';
        }
        if($g['customer_prototypes']!=json_encode($item['customer_prototypes'])){
            $new_data['customer_prototypes'] = json_encode($item['customer_prototypes']);
            $msg[] = '套餐信息customer_prototypes有更新';
        }
        if($g['tax_percentage']!=$item['tax_percentage']){
            $new_data['tax_percentage'] = $item['tax_percentage'];
            $msg[] = '税率有更新,由原来的'.$g['tax_percentage'].'更新为'.$new_data['tax_percentage'];
            $update_tax = 1;//税率影响价格 必须更新价格缓存
        }
        $usd_price_section = $this->getItemUsdMaxAndMinPrice($item);
        if($g['usd_price_section']!=$usd_price_section){
            $new_data['usd_price_section'] = $usd_price_section;
            $msg[] = '售价有更新,由原来的'.$g['usd_price_section'].'更新为'.$new_data['usd_price_section'];
            $update_price_section = 1;
        }
        $new_data['item_json'] = json_encode($item);
        $new_data['update_time'] = time();
        $new_data['update_desc'] = $g['update_desc'].'##'.date("Y-m-d H:i:s").'----'.implode('----',$msg);
        if(in_array($g['fare_goods_id'],$link_source_ids)){
            $new_data['is_update'] = 1;
        }

        db("fareharbor_goods")->where("fare_goods_id",$g['fare_goods_id'])->update($new_data);
        $this->wirteFareLog("更新item_id为{$g['item_id']}的商品成功;更新说明:".json_encode($msg));
        if($update_tax==1){//税率更新 更新价格缓存
            $this->cacheEveryItemSpecs($g['company'],$g['item_id']);
        }

        if($update_price==1){//价格更新 更新相关价格
            $this->updateFareGoodsPriceSction($g['fare_goods_id'],$new_data['usd_price_section']);
        }

    }

    //更新价格区间
    public function updateFareGoodsPriceSction($fare_goods_id,$new_usd_price_section)
    {

        $new_cny_price_section = $this->getItemSellPrice($new_usd_price_section);
        //更新关联商品的价格
        db("goods")->where(['source_id'=>$fare_goods_id,'channel_source'=>'fareharbor'])->update(['price_section'=>$new_cny_price_section]);
    }

    protected function wirteFareLog($msg,$file='updfare'){
        $filename = RUNTIME_PATH.'/'.$file.'-'.date('Y-m-d').'.txt';
        file_put_contents($filename,date('H:i:s').'--'.$msg."\n",FILE_APPEND);
    }

    //同步更新商品价格表
    protected function syncUpdGoodsPriceByFareharbor(){
        $faregoods = db("fareharbor_goods")->field('fare_goods_id,usd_price_section')->where(['status'=>'1'])->select();
        if(!empty($faregoods)){
            foreach ($faregoods as $key=>$value){
                $price_section = $this->getItemSellPrice($value['usd_price_section']);
                db("goods")->where([
                    'standard_pro'=>1,
                    'channel_source'=>'fareharbor',
                    'source_id'=>$value['fare_goods_id']
                ])->update(['price_section'=>$price_section]);
            }
        }
    }

    //将套餐名中英文转换 (new V())->etocTencent($string) 用于接口转换
    public function enTransChSpecName($string){
        $config = [
            'Adult'=>'成人',
            'Child'=>'儿童',
            'Infant'=>'婴儿'
        ];

        if(array_key_exists($string,$config)){
            $chinese_name = $config[$string];
        }else{
            $chinese_name = (new V())->etocTencent($string);
        }

        return empty($chinese_name)?$string:$chinese_name;
    }

    public function chNameByItemCustomer($customer_prototypes,$item){
        $specsName = db('faregoods_specname')->where('item_id',$item)->select();
        if(!empty($specsName)){
            $specsEnName = array_column($specsName,'en_name');
        }else{
            $specsEnName = [];
        }
        //翻译名称
        foreach ($customer_prototypes as $i=>$s){
            if(array_search($s['display_name'],$specsEnName)!==false){
                $ch_name = $specsName[array_search($s['display_name'],$specsEnName)]['ch_name'];
            }
            $customer_prototypes[$i]['display_cname'] = empty($ch_name)?$s['display_name']:$ch_name;
        }

        return $customer_prototypes;
    }

    //返回对从明天起到180天的价格数据
    public function getPackageByLastMonth($company,$item,$local_exchange,$startTime='',$month_num=3)
    {
        $packages = [];
        $startTime = !empty($startTime)?$startTime:time();
        $start_time = $begin_time = strtotime('+1 day',strtotime(date('Y-m-d',$startTime)));//开始日期时间戳
        $end_time = strtotime('+'.$month_num.' months',strtotime(date('Y-m-01',$startTime)));//月份的截止日期
        $days_num = ( $end_time - $start_time ) / (24 * 3600);//总共天数
        $specsName = db('faregoods_specname')->where('item_id',$item)->select();
        //获取farehabor利润点
        $sell_rate = db('viator_discount')->where("id=2 and status=1")->find();
        $sell_percent_rate = empty($sell_rate)&&$sell_rate['discount_num']?1:$sell_rate['discount_num'];
        for ($i=0;$i < $days_num;$i++){
            $sdate = date("Y-m-d",$begin_time + $i*24*3600);
            $cache = Cache::get('fare_'.$company.'_'.$item.'_'.$sdate);
            if(!empty($cache)){
                $cache = json_decode($cache,true);
                //获取具体套餐信息
                if(!empty($cache[0])){
                    $details = $cache[0];
                    $specs = [];
                    foreach ($details['customer_type_rates'] as $customer_type_rate){
                        $display_name = "";
                        foreach ($specsName as $s_name){
                            if($s_name['en_name']==$customer_type_rate['customer_prototype']['display_name']){
                                $display_name = $s_name['ch_name'];break;
                            }
                        }
                        //total_including_tax 单位美分
                        $fareharbor_price = ceil($customer_type_rate['customer_prototype']['total_including_tax']*$sell_percent_rate)/100;
                        $fareharbor_cny_price = ceil($customer_type_rate['customer_prototype']['total_including_tax']*$sell_percent_rate*$local_exchange)/100;
                        $specs[] = [
                            'packageId'=>0,
                            'packageName'=>'DEFAULT',
                            'specId'=>$customer_type_rate['customer_prototype']['pk'],
                            'specName'=>!empty($display_name)?$display_name:$customer_type_rate['customer_prototype']['display_name'],
                            'specStock'=>999,
                            'specPersonsIncUnit'=>1,
                            'specPersonsPerUnit'=>1,
                            'specMarketPricePerPerson'=>$fareharbor_price,
                            'specPricePerPerson'=>$fareharbor_price,
                            'specMarketPricePerPersonCNY'=>$fareharbor_cny_price,
                            'specPricePerPersonCNY'=>$fareharbor_cny_price,
                        ];
                    }

                    $packages[] = [
                        'time'=>substr($details['start_at'],0,10),
                        'specs'=>$specs
                    ];
                }
            }
        }

        return $packages;
    }

    //返回对某一天的价格数据
    public function getPackageByOneDay($company,$item,$local_exchange,$date,$personIds=[])
    {
        $result = [];
        $specsName = db('faregoods_specname')->where('item_id',$item)->select();
        //获取farehabor利润点
        $sell_rate = db('viator_discount')->where("id=2 and status=1")->find();
        $sell_percent_rate = empty($sell_rate)&&$sell_rate['discount_num']?1:$sell_rate['discount_num'];
        $packages = [];
        $cache = Cache::get('fare_'.$company.'_'.$item.'_'.$date);
        if(!empty($cache)){
            $cache = json_decode($cache,true);
            //获取具体套餐信息
            if(!empty($cache[0])){
                $details = $cache[0];
                $specs = [];
                foreach ($details['customer_type_rates'] as $customer_type_rate){
                    if(empty($personIds) ||  (!empty($personIds) && in_array($customer_type_rate['pk'],$personIds))){
                        $display_name = "";
                        foreach ($specsName as $s_name){
                            if($s_name['en_name']==$customer_type_rate['customer_prototype']['display_name']){
                                $display_name = $s_name['ch_name'];break;
                            }
                        }
                        //total_including_tax 单位美分
                        $fareharbor_price = ceil($customer_type_rate['customer_prototype']['total_including_tax']*$sell_percent_rate)/100;
                        $fareharbor_cny_price = ceil($customer_type_rate['customer_prototype']['total_including_tax']*$sell_percent_rate*$local_exchange)/100;
                        $specs[] = [
                            'personId'=>$customer_type_rate['pk'],
                            'specId'=>$customer_type_rate['customer_prototype']['pk'],
                            'specName'=>!empty($display_name)?$display_name:$customer_type_rate['customer_prototype']['display_name'],
                            'specStock'=>999,
                            'specPersonsIncUnit'=>1,
                            'specPersonsPerUnit'=>1,
                            'specMarketPricePerPerson'=>$fareharbor_price,
                            'specPricePerPerson'=>$fareharbor_price,
                            'specMarketPricePerPersonCNY'=>$fareharbor_cny_price,
                            'specPricePerPersonCNY'=>$fareharbor_cny_price,
                        ];
                    }
                }

                $packages[] = [
                    'packageId'=>0,
                    'packageName'=>'DEFAULT',
                    'specs'=>$specs
                ];
            }
        }


        return $packages;
    }
    //对不可售的faerharbor商品进行价格监测 一旦可售修改可售状态并提醒业务人员查看
    public function monitorNotSaleFareharbor()
    {
        ignore_user_abort();//关闭浏览器仍然执行
        set_time_limit(0);//程序运行不停止
        //1 查找到所有不可售的fareharbor商品
        $notSaleFareGoods = db('fareharbor_goods')->field('fare_goods_id,item_id,company,status')->where([
            'status'=>0,//不可售状态
        ])->select();
        if(empty($notSaleFareGoods)){
            $this->wirteFareLog("未检测到不可售FareGoods数据");
            return false;
        }
        $this->wirteFareLog("【数据库】共检测到不支持售卖的数据".count($notSaleFareGoods)."条");
        //2 检查180内是否可售
        $availableFareGoods = $availableFareGoodsMsg = [];
        foreach ($notSaleFareGoods as $key=>$value){
            //获取180的价格数据
            //获取1-100天数据
            $firstData = $this->getHundredProDetail($value['company'],$value['item_id'],'','');
            //获取101-180天数据
            $sdate = date('Y-m-d',strtotime("+100 day",time()));
            $secondData = $this->getHundredProDetail($value['company'],$value['item_id'],$sdate,'80');
            $availabilities = array_merge($firstData,$secondData);
            //3 不可售跳过 可售加入提醒邮件
            if(empty($availabilities)) continue;
            $availableFareGoods[] = $value['fare_goods_id'];
            $availableFareGoodsMsg[] = 'ItemID为【'.$value['item_id'].'】的【'.$value['company'].'】商品，180天内可售';
        }
        if(empty($availableFareGoods)){
            $this->wirteFareLog("不支持售卖的商品180天内均不可售");
            return false;
        }else{
            $this->wirteFareLog("【接口】共检测到可售FareGoods数据".count($availableFareGoods)."条");
            $this->wirteFareLog("开始更新fareharbor_goods表");
            db::startTrans();
            try{
            	//更新可售状态
                db('fareharbor_goods')->where(['fare_goods_id'=>['in',$availableFareGoods]])->update([
                        'status'=>1,
                        'update_time'=>time()
                    ]);
                db::commit();
                $this->wirteFareLog("更新fareharbor_goods表数据成功");
            }catch (Exception $e){
                db::rollback();
                $errorMsg = "更新fareharbor_goods表数据失败，".$e->getMessage();
                $this->wirteFareLog($errorMsg);
                (new \app\wap\controller\Notify())->kbxemailcode('Fareharbor商品可售状态修改失败提醒',$errorMsg,config('XIAOMEI_NOTICE_EMAIL'));
                return $errorMsg;
            }
        }
        //4 如果存在可售商品 发送邮件提醒业务人员查看
        if(!empty($availableFareGoodsMsg)){
            $this->wirteFareLog(implode("\n",$availableFareGoodsMsg));
            (new \app\wap\controller\Notify())->kbxemailcode('Fareharbor商品检测变更可售邮件提醒',
                implode('<br>',$availableFareGoodsMsg),config('XIAOMEI_NOTICE_EMAIL'));
        }
        return true;
    }
}